<template>
	<view class="division-device">
		<g-navbar title="划分设备" />
		<view class="main">
			<deviceList @clickAllocated="clickAllocated" ref="deviceListRef" />
		</view>
		<chooseAgentPopup ref="chooseAgentPopupRef" :activeList="activeDeviceList" @clickChooseAgent="clickChooseAgent"
			:currentAgent="currentAgent" @confirmAppropriate="confirmAppropriate" />
		<agentListPopup ref="agentListPopupRef" :agentList="agentList" @selectAgent="selectAgent" />
	</view>
</template>

<script lang="ts" setup>
	import deviceList from './components/device-list/deviceList';
	import chooseAgentPopup from './components/choose-agent-popup/chooseAgentPopup';
	import agentListPopup from './components/agent-list-popup/agentListPopup';
	import { IDevice } from './components/device-item/types';
	import { ref, Ref } from 'vue';
	import { IPopupExpose } from './types';
	import REST_URL from '@/http/http.restUrl';
	import { onLoad } from '@dcloudio/uni-app';
	import { IAgent, ITempItem } from './components/agent-list-popup/types';
	import {IDeviceListExpose} from './components/device-list/types';


	const chooseAgentPopupRef : Ref<IPopupExpose | null> = ref(null);

	const agentListPopupRef : Ref<IPopupExpose | null> = ref(null);

	const activeDeviceList : Ref<IDevice[]> = ref([]);

	const agentList : Ref<IAgent[]> = ref([]);

	const deviceListRef : Ref<IDeviceListExpose | null> = ref(null);

	const currentAgent : Ref<ITempItem | null> = ref(null);



	const clickAllocated = (activeList : IDevice[]) => {
		chooseAgentPopupRef.value?.open();
		activeDeviceList.value = activeList;
	}

	const clickChooseAgent = () => {
		agentListPopupRef.value?.open();
	}

	onLoad(async () => {
		await uni.loginManger.$interceptor;
		getAgentList();
	})

	const getAgentList = async () => {
		const result : IAgent[] = (await uni.http.POST(REST_URL.getAgentList)).data;
		agentList.value = result;
	}

	const selectAgent = (e : ITempItem) => {
		currentAgent.value = e;
	}

	const confirmAppropriate = async () => {
		if (!currentAgent.value) {
			return uni.prompt.$showToast('请选择代理商')
		}

		const snList = activeDeviceList.value.map(item => item.model_sn).join(",");

		await uni.http.POST(REST_URL.confirmAppropriate, {
			agent_id: currentAgent.value.id,
			model_sn: snList,
		})
		uni.prompt.$showToast('划拨成功');
		chooseAgentPopupRef.value?.close!();
		currentAgent.value = null;
		deviceListRef.value?.refreshList();
	}
</script>

<style scoped lang="scss">
	@import "./divisionDevice.scss";
</style>